package com.java.service;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.java.control.search.ConditionPart;
import com.java.control.search.SearchCond;
import com.java.control.search.SearchStat;
import com.java.dao.HinbernateEntityDao;

/**
 * 服务基类
 * @author wqf
 * @version  Nov 22, 2011 9:10:21 AM
 */
@Transactional(propagation = Propagation.REQUIRED,readOnly=false, rollbackFor = Exception.class)
public class BaseService {
	
	private static Logger logger = Logger.getLogger(BaseService.class);
			
	public HinbernateEntityDao dao;

	public HinbernateEntityDao getDao() {
		return dao;
	}

	public void setDao(HinbernateEntityDao dao) {
		this.dao = dao;
	}
	/**
	 * 
	 * @param <T>
	 * @param hql
	 * @return
	 */
	public <T> List<T> searchForHQL(String hql){
		return this.dao.loadObjects(hql, null, null, false, null);
	}
	/**
	 * 
	 * @param <T>
	 * @param cls
	 * @param sql
	 * @return
	 */
	public <T> List<T> searchForSQL(Class cls,String sql){
		return this.dao.loadObjectsNativeSQL(cls,sql);
	}
	
	/**
	 * 如果不是第一次分页查询，则不再查询总记录数 ,记录总数通过url传递
	 * @param <T>
	 * @param cls
	 * @param cond
	 * @return
	 */
	public <T> SearchStat getSearchStat(Class<T> cls,SearchCond cond) {
		SearchStat searchStat = new SearchStat();
		searchStat.setPageSize(cond.getPageSize());
		if(cond.getTotalCount()>0){
			searchStat.setTotalCount(cond.getTotalCount());		
		}else{
			searchStat.setTotalCount(getStatCount(cls,cond));
		}
		return searchStat;
	}
	
	/**
	 * 查询总条数
	 * @param <T>
	 * @param cls
	 * @param cond
	 * @return
	 */
	public <T> Long getStatCount(Class<T> cls,SearchCond cond) {
		ConditionPart condPart = cond.getCondition();
		Object[] params = (Object[])condPart.getParams().toArray(new Object[0]);
		return this.dao.getObjectCount(cls, condPart.getExpression(), params);
		
	}
	
	public <T> List<T> search(Class<T> cls) {
		List<T> objs = this.dao.loadObjects(cls);
		return objs;
	}
	
	public <T> List<T> search(Class<T> cls, SearchCond cond) {
		ConditionPart condPart = cond.getCondition();
		Object[] params = (Object[])condPart.getParams().toArray(new Object[0]);
		List<T> objs = this.dao.loadObjects(cls, condPart.getExpression(), null,cond.getPageSize(), cond.getPageIndex(), params);
		return objs;
	}
	
	public <T> List<T> search(Class<T> cls, SearchCond cond, String orderBy) {
		ConditionPart condPart = cond.getCondition();
		Object[] params = (Object[])condPart.getParams().toArray(new Object[0]);
		List<T> objs = this.dao.loadObjects(
				cls, condPart.getExpression(), orderBy, cond.getPageSize(), cond.getPageIndex(), params);		
		return objs;
	}
	
}
